layui.use(function () {
  var table = layui.table;
  var form = layui.form;
  var laydate = layui.laydate;

  var deviceId;

  initTable();

  form.on('submit(search)', function (data) {
    initTable();
    return false;
  });

  form.on('submit(search-history)', function (data) {
    initHistoryTable();
    return false;
  });

  form.on('submit(search-chartHistory)', function (data) {
    if (!$('#search-chartDate').val()) {
      layer.msg('请选择日期范围！');
    } else {
      getTrendList();
    }
    return false;
  });

  function initTable() {
    var height = $('.contain').innerHeight() - 98 - 26;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/data/device/water/status/list',
      where: {
        name: $('#search-name').val(),
        code: $('#search-code').val(),
        type: $('#search-type').val(),
        eventType: $('#search-eventType').val(),
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '设备名称',
            align: 'center',
          },
          {
            field: 'code',
            title: '设备号',
            align: 'center',
          },
          {
            field: 'typeDesc',
            title: '设备类型',
            align: 'center',
          },
          {
            field: 'eventTypeDesc',
            title: '告警类型',
            align: 'center',
          },
          {
            field: 'signal',
            title: '信号强度',
            align: 'center',
          },
          {
            field: 'temperature',
            title: '温度(℃)',
            align: 'center',
          },
          {
            field: 'voltage',
            title: '电压(mV)',
            align: 'center',
          },
          {
            field: 'ntu',
            title: '浊度',
            align: 'center',
          },
          {
            field: 'dataTime',
            title: '上报时间',
            align: 'center',
          },
          {
            field: '',
            title: '操作',
            align: 'center',
            width: 150,
            templet: '#operate',
          },
        ],
      ],
    });

    table.on('tool(filter)', function (obj) {
      //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data, //获得当前行数据
        layEvent = obj.event; //获得 lay-event 对应的值
      if (layEvent === 'detail') {
        var flag = false;
        deviceId = data.deviceId;
        layer.open({
          type: 1,
          title: '详情',
          skin: 'default-class',
          area: ['14rem', '8rem'],
          closeBtn: 2,
          // shade: false,
          move: false,
          closeBtn: 2,
          id: 1, //设置该值后，不管是什么类型的层，都只允许同时弹出一个。
          content: `<div style="margin: .3rem;height:calc(100% - .6rem)">
                      <div class="tab">
                        <div class="tab-item active" data-type="1">浊度趋势</div>
                        <div class="tab-item" data-type="2">历史记录</div>
                      </div>
                      <div id="tab1" style="height: calc(100% - .3rem);">
                        <div class="search-bar layui-form">
                          <div>
                              <input type="text" name="code" id="search-chartDate" placeholder="请选择日期范围" autocomplete="off"
                        class="layui-input">
                          </div>
                          <button class="layui-btn" lay-submit lay-filter="search-chartHistory">查询</button>
                        </div>
                        <div id="chart" style="height: calc(100% - .98rem)"></div>
                      </div>
                      <div id="tab2" style="display:none;">
                        <div class="search-bar layui-form">
                          <div>
                            <select id="search-hisEventType">
                                <option value="">请选择类型</option>
                                <option value="0">正常</option>
                                <option value="101">浊度告警</option>
                            </select>
                          </div>
                          <div>
                              <input type="text" name="code" id="search-date" placeholder="请选择日期范围" autocomplete="off"
                        class="layui-input">
                          </div>
                          <button class="layui-btn" lay-submit lay-filter="search-history">查询</button>
                        </div>
                        <table id="history-table"></table>
                      </div>
                    </div>`, //这里content是一个普通的String
          success: function (layero, index) {
            laydate.render({
              elem: '#search-chartDate',
              range: true, //或 range: '~' 来自定义分割字符
              value: getBeforeDate(-6) + ' - ' + getBeforeDate(0),
            });

            getTrendList();

            $('.tab-item').click(function (e) {
              var type = $(this)[0].dataset.type;
              $(e.currentTarget)
                .addClass('active')
                .siblings()
                .removeClass('active');

              if (type == '1') {
                $('#tab1').show();
                $('#tab2').hide();
              } else {
                if (!flag) {
                  laydate.render({
                    elem: '#search-date',
                    range: true, //或 range: '~' 来自定义分割字符
                  });
                  form.render();
                  initHistoryTable();
                  flag = true;
                }
                $('#tab1').hide();
                $('#tab2').show();
              }
            });
          },
        });
      }
    });
  }

  function initHistoryTable() {
    var height = $('.layui-layer-content').innerHeight() - 98 - 36 - 60;

    //第一个实例
    table.render({
      title: '',
      height: height,
      text: {
        none: '暂无数据',
      },
      elem: '#history-table',
      skin: 'nob',
      headers: {
        SessionId: JSON.parse(localStorage.getItem('userInfo')).sessionId,
      },
      url: ajaxPrefix() + '/data/device/water/history/list',
      where: {
        deviceId: deviceId,
        eventType: $('#search-hisEventType').val(),
        beginDate: $('#search-date').val().substring(0, 10),
        endDate: $('#search-date').val().substring(13, 24),
      },
      parseData: function (res) {
        //res 即为原始返回的数据
        return {
          code: res.status == 200 ? 0 : 1, //解析接口状态
          msg: res.message, //解析提示文本
          count: res.result?res.result.total:0, //解析数据长度
          data: res.result?res.result.data:[], //解析数据列表
        };
      },
      request: {
        pageName: 'pageNum', //页码的参数名称，默认：page
        limitName: 'pageSize', //每页数据量的参数名，默认：limit
      },
      page: {
        //开启分页
        limit: 10,
      },
      cols: [
        [
          //表头
          {
            field: 'name',
            title: '设备名称',
            align: 'center',
          },
          {
            field: 'code',
            title: '设备号',
            align: 'center',
          },
          {
            field: 'typeDesc',
            title: '设备类型',
            align: 'center',
          },
          {
            field: 'eventTypeDesc',
            title: '告警类型',
            align: 'center',
          },
          {
            field: 'signal',
            title: '信号强度',
            align: 'center',
          },
          {
            field: 'temperature',
            title: '温度(℃)',
            align: 'center',
          },
          {
            field: 'voltage',
            title: '电压(mV)',
            align: 'center',
          },
          {
            field: 'ntu',
            title: '浊度',
            align: 'center',
          },
          {
            field: 'dataTime',
            title: '上报时间',
            align: 'center',
            width: 180,
          },
        ],
      ],
    });
  }

  function getTrendList() {
    AjaxRequest(
      '/data/device/water/trend/list?deviceId=' +
        deviceId +
        '&beginDate=' +
        $('#search-chartDate').val().substring(0, 10) +
        '&endDate=' +
        $('#search-chartDate').val().substring(13, 24),
      callBack
    );

    function callBack(result) {
      if (result.status == 200) {
        var data = result.result;
        var xData = [];
        var yData = [];
        $.each(data, function (i, e) {
          xData.push(e.dataTime);
          yData.push(e.ntu);
        });
        drawTrendChart(xData, yData);
      }
    }
  }

  function drawTrendChart(xData, yData) {
    var option = {
      tooltip: {
        trigger: 'axis',
      },

      grid: {
        left: '8%',
        top: 40,
        bottom: 30,
        right: '5%',
        containLabel: false,
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xData,
        axisLine: { show: false },
        axisLabel: {
          color: '#99A4B7',
          formatter: function (value) {
            // 对日期格式进行自定义，可以根据需要调整
            return value.split(' ').join('\n');
          },
        },
        axisTick: { show: false },
        splitLine: {
          show: false,
        },
      },
      yAxis: {
        name: 'ntu',
        type: 'value',
        axisLine: { show: false },
        axisLabel: { color: '#99A4B7' },
        axisTick: { show: false },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: 'rgba(255,255,255,0.1)',
            dashOffset: 1,
          },
        },
      },
      series: [
        {
          name: 'ntu',
          type: 'line',
          data: yData,
          symbol: 'none',
          markPoint: {
            symbolSize: '29',
            symbol:
              'image://',
            label: {
              show: false,
            },
            data: [
              {
                type: 'max',
                name: '最大值',
              },
            ],
          },
          itemStyle: {
            normal: {
              borderWidth: 3,
              //4个参数用于配置渐变色的起止位置, 这4个参数依次对应右/下/左/上四个方位
              color: '#3F91D8',
            },
          },
          areaStyle: {
            normal: {
              origin: 'start',
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                {
                  offset: 0,
                  color: 'rgba(10, 71, 118, 0)',
                },
                {
                  offset: 1,
                  color: 'rgba(10, 71, 118, 0.71)',
                },
              ]),
            },
          },
        },
      ],
    };

    var chart = echarts.init(document.getElementById('chart'));
    chart.setOption(option);
  }
});
